import {
  BadRequestException,
  Injectable,
  InternalServerErrorException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
  DeliverGoodsDto,
  GetOrderDto,
  ReceivedGoodsDto,
} from "../dto/order.dto";
import { Goods } from "/@/entities/goods/Goods.entity";
import { Order } from "/@/entities/order/Order.entity";
import { User } from "/@/entities/user/User.entity";
import { OrderEnum } from "/@/enum/order.enum";
import { GetOrderByIdDto } from "/@/logical/weappModule/dto/order.dto";
import { format } from "/@/utils/moment";
@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>,
    @InjectRepository(Order)
    private orderRepository: Repository<Order>,
  ) {
    //
  }

  /**
   * 获取订单 根据id
   * @param query 字段
   */
  async getOrderById(query: GetOrderByIdDto) {
    try {
      const { id } = query;
      const order: any = await this.orderRepository.findOne(id, {
        relations: ["carts"],
      });

      const userData = await this.userRepository.findOne({
        id: order.user_id,
      });

      for (let i = 0; i < order.carts.length; i++) {
        order.carts[i].goods = await this.goodsRepository.findOne({
          id: parseInt(order.carts[i].goods_id),
        });
      }
      order.userData = userData;
      order.create_at = format(order.create_at, "YYYY-MM-DD HH:mm:ss");
      order.update_at = format(order.update_at, "YYYY-MM-DD HH:mm:ss");
      return order;
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 获取该订单id下的购物列表
   * @param query 字段
   */
  async getOrderCartById(query: GetOrderByIdDto) {
    try {
      const { id } = query;
      const order: any = await this.orderRepository.findOne(id, {
        relations: ["carts"],
      });

      for (let i = 0; i < order.carts.length; i++) {
        order.carts[i].goods = await this.goodsRepository.findOne({
          id: parseInt(order.carts[i].goods_id),
        });
      }
      console.log(order.carts);
      const carts = order.carts.map((item) => {
        item.urls = item.goods.urls.split(",");
        item.name = item.goods.name;
        item.price = item.goods.price;
        item.total_price = item.goods.price * item.goods_num;
        item.create_at = format(item.create_at, "YYYY-MM-DD HH:mm:ss");
        item.update_at = format(item.update_at, "YYYY-MM-DD HH:mm:ss");
        return item;
      });

      return carts;
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 获取Order列表
   * @param query 字段
   */
  async getOrderList(query: GetOrderDto) {
    const { pageSize = 10, page = 1, id, status, phone } = query;
    try {
      let qb = this.orderRepository.createQueryBuilder("order");
      qb = qb.limit(pageSize).offset((page - 1) * pageSize);

      if (id) {
        qb = qb.andWhere("order.id = :id", { id });
      }
      if (status && status !== "0") {
        qb = qb.andWhere("order.status = :status", { status });
      }
      if (phone) {
        qb = qb.andWhere("order.phone = :phone", { phone });
      }
      qb = qb.leftJoinAndSelect(User, "user", "user.id = order.user_id").select(
        `order.id as id,
        order.total_price as total_price,
        order.status as status,
        order.user_id as user_id,
        user.nickName as nickName,
        user.avatarUrl as avatarUrl,
        order.name as name,
        order.phone as phone,
        order.address as address,
        order.create_at as create_at,
        order.update_at as update_at`,
      );
      const items = await qb.getRawMany();
      items.map((item) => {
        item.avatarUrl = item.avatarUrl ? item.avatarUrl.split(",") : [];
        item.create_at = format(item.create_at, "YYYY-MM-DD HH:mm:ss");
        item.update_at = format(item.update_at, "YYYY-MM-DD HH:mm:ss");
        return item;
      });
      const total = await qb.getCount();
      return { items, total };
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 标记发货
   * @param params 字段
   */
  async deliverGoods(params: DeliverGoodsDto) {
    const { id, express_no } = params;

    const swiper = await this.orderRepository.findOne({ id });
    if (!swiper) {
      throw new BadRequestException("查无此订单");
    }
    if (swiper.status !== OrderEnum.SHIPPED) {
      throw new BadRequestException("订单状态有误");
    }
    await this.orderRepository.update(id, {
      express_no,
      status: OrderEnum.RECEIVED,
    });
    return "ok";
  }

  /**
   * 标记收货，完成订单
   * @param params 字段
   */
  async receivedGoods(params: ReceivedGoodsDto) {
    const { id } = params;

    const swiper = await this.orderRepository.findOne({ id });
    if (!swiper) {
      throw new BadRequestException("查无此订单");
    }
    if (swiper.status !== OrderEnum.RECEIVED) {
      throw new BadRequestException("订单状态有误");
    }
    await this.orderRepository.update(id, { status: OrderEnum.FINISH });
    return "ok";
  }
}
